import { useImmer } from 'use-immer'

interface User {
  name: string
  age: number
  profile: {
    avatar: string
    bio: string
    preferences: {
      theme: 'light' | 'dark'
      notifications: boolean
    }
  }
}

export default function UseImmerObjExample() {
  const [user, setUser] = useImmer<User>({
    name: '大满zs',
    age: 25,
    profile: {
      avatar: '/avatar.jpg',
      bio: '前端开发者',
      preferences: {
        theme: 'light',
        notifications: true
      }
    }
  })

  const updateTheme = () => {
    setUser(draft => {
      draft.profile.preferences.theme = 'dark'
      // 如果用 useState 的话，只能这样修改，繁琐且可读性差
      // setUser(prevUser => ({
      //   ...prevUser,
      //   profile: {
      //     ...prevUser.profile,
      //     preferences: {
      //       ...prevUser.profile.preferences,
      //       theme: 'dark'
      //     }
      //   }
      // }))
    })
  }

  const updateBio = (newBio: string) => {
    setUser(draft => {
      draft.profile.bio = newBio
    })
  }

  return (
    <div className="user-profile">
      <h1>Object</h1>
      <h2>{user.name}</h2>
      <p>年龄: {user.age}</p>
      <p>个人简介: {user.profile.bio}</p>
      <p>主题: {user.profile.preferences.theme}</p>

      <button onClick={updateTheme}>切换主题</button>
      <button onClick={() => updateBio('热爱编程的开发者')}>
        更新简介
      </button>
    </div>
  )
}